<template>
    <page-box class="custom-page-box">
        <template v-slot:header>
            <ask-breadcrumb>
                <template v-for="(item, index) in $getBreadCrumbsName($route.path)">
                    <ask-breadcrumb-item :key="index" v-if="item.path" :to="'/' + item.path">{{ item.meta.title }}</ask-breadcrumb-item>
                    <ask-breadcrumb-item :key="index" v-else>{{ item.meta.title }}</ask-breadcrumb-item>
                </template>
            </ask-breadcrumb>
        </template>
        <div class="only-word" v-if="onlyWord">
            唯一性<span class="tips">(多条唯一性时，满足1个即可)</span>：<span class="word" :title="onlyWord">{{ onlyWord }}</span>
        </div>
        <div class="form-item-manage-container">
            <div class="container-left">
                <div class="container-left-body">
                    <el-button class="add-btn" type="primary" @click="addItem">添加分类</el-button>
                    <div class="scroll-box" v-if="treeData[0] && treeData[0].children.length">
                        <org-tree
                            ref="OrgTree"
                            :treeData="treeData"
                            :value="typeId"
                            :clickNodeExpand="false"
                            :filterWord="filterInput"
                            :canEdit="true"
                            :canDrag="false"
                            :canDelete="false"
                            :canUpdate="true"
                            :maxLevel="3"
                            @handleItem="handleItem"
                            @clickNode="clickNode"
                            @addDepartment="addDepartment"
                            @deleteDepartment="deleteDepartment"
                        />
                    </div>
                </div>
            </div>
            <div class="container-right">
                <resource-all ref="ResourceAll" :typeId="typeId" :nowLevel="nowLevel" :currentNode="currentNode" @changeOnly="changeOnly"/>
            </div>
        </div>
    </page-box>
</template>

<script lang="ts">
import Vue from "vue";
import { Component } from "vue-property-decorator";
import ResourceAll from "./src/all.vue";
import ResourceDepartment from "./src/department.vue";
import ResourceLabel from "./src/label.vue";
import OrgTree from "../../../../components/org-tree/index.vue";
import { State } from "vuex-class";
import { dialogCategory } from "../components/add-category/index";
@Component({
    components: {
        ResourceAll,
        ResourceDepartment,
        ResourceLabel,
        OrgTree
    }
})
export default class ResourceManage extends Vue {
    @State(state => state.authArea) authArea: any;
    // 当前用户所处层级菜单
    get client() {
        return this.$getUserLevel(this.authArea.orgCategoryId).name;
    }

    get _isOperation() {
        return ["ADMIN", "OPERATION_ADMIN", "OPERATION"].includes(this.client);
    }

    // 树结构数据
    treeData: any = [];
    // 当前组织id
    typeId = "";
    // 过滤部门
    filterInput = "";
    // 当前组织数据
    currentNode: any = {};
    // 数据总数
    total = 0;
    // 每页数量
    pageSize = 10;
    // 当前页码
    pageIndex = 1;
    // 表格数据
    tableData = [];
    // 当前层级
    nowLevel = 0;
    onlyWord = ""

    created() {
        this.getTree();
    }

    // 获取部门树
    async getTree() {
        const res = await this.$server["business/config/tree"]({
            data: {}
        });
        if (res.data.code === 200) {
            this.typeId = "";
            this.currentNode = {};
            this.treeData = res.data.data;
            this.total = 0;
            this.pageSize = 10;
            this.pageIndex = 1;
            this.tableData = [];
            if (res.data.data.length) {
                this.typeId = res.data.data[0].id;
                this.currentNode = res.data.data[0];
            }
        } else {
            this.typeId = "";
            this.currentNode = {};
            this.treeData = [];
            this.$message.error(res.data.message || "接口请求错误!");
        }
    }

    handleItem(payload: any) {
        const { data } = payload;
        dialogCategory({
            model: {
                name: data.name || "",
                field: data.field || "",
                id: data.id || "",
                icon: data.icon || "",
                color: data.color
            },
            showIcon: [1, 2].includes(payload.nowLevel),
            iconList: data.icon ? [data.icon] : [],
            showColor: payload.nowLevel === 1,
            close: () => {
                (this.$refs.OrgTree as any).closeInput();
            },
            sure: async(vm: any, model: any) => {
                (this.$refs.OrgTree as any).addDepartment(
                    {
                        field: model.field,
                        id: model.id,
                        name: model.name,
                        icon: model.icon,
                        parentId: data.parentId,
                        color: model.color
                    },
                    "notDeal"
                );
                this.$nextTick(() => {
                    vm.close();
                });
            }
        });
    }

    // 点击节点获取列表
    clickNode(data: any) {
        const { id } = data;
        this.nowLevel = ((this.$refs.OrgTree as any).$refs.tree as any).getNode(id).level - 1;
        if (this.typeId !== id) {
            ((this.$refs.ResourceAll as any).$refs.multipleTable as any).clearSelection();
        }
        this.currentNode = data;
        this.typeId = id;
        (this.$refs.ResourceAll as any).getTable(id);
        this.changeOnly(this.typeId);
    }

    async getOnlyWord() {
        const res = await this.$server["business/getOnly"]({
            data: {
                typeId: this.typeId
            }
        });
        if (res.data.code === 200) {
            const list: any[] = res.data.data.map((item: any) => item.map((it: any) => it.labelName));
            this.onlyWord = list.map((item: any, index: number) => (index + 1) + "." + item.join("+")).join(" ");
        } else {
            this.onlyWord = "";
        }
    }

    // 添加一级部门
    addItem() {
        (this.$refs.OrgTree as any).addItem("", "", 1);
    }

    // 添加/编辑部门
    async addDepartment(data: any) {
        const { id, name, field, parentId, tier, icon, color } = data;
        const url = id ? "business/updateCategory" : "business/addCategory";
        const response: any = await this.$server[url]({
            data: {
                id,
                name,
                field,
                parentId,
                tier,
                icon,
                color
            }
        });
        if (response.data.code === 200) {
            this.$message.success("操作成功");
            this.getTree();
        } else {
            this.$message.error(response.data.message || "接口请求错误!");
        }
    }

    // 删除部门
    async deleteDepartment(data: any, callback: any) {
        let flag = false;
        if (this.total > 0) {
            this.$message.error("该分类下存在表单项，无法执行删除");
            callback(flag);
        } else {
            this.$confirm("是否确定要删除分类?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(async() => {
                    const res = await this.$server["business/delCategory"]({
                        params: {
                            id: data.id
                        }
                    });
                    if (res.data.code === 200) {
                        flag = true;
                        if (data.id === this.typeId) {
                            this.clickNode(this.treeData[0]);
                        }
                        callback(flag);
                    } else {
                        this.$message.error(
                            res.data.message || "接口请求错误!"
                        );
                    }
                })
                .catch(() => {
                    callback(flag);
                });
        }
    }

    changeOnly(id?: any) {
        if (id !== this.typeId) return false;
        if (this.nowLevel === 2) {
            this.getOnlyWord();
        } else {
            this.onlyWord = "";
        }
    }
}
</script>

<style scoped lang="scss">
::v-deep {
    .page-base-body {
        height: calc(100% - 50px) !important;
    }
}
.custom-page-box {
    position: relative;
    .only-word {
        position: absolute;
        left: 290px;
        top: 10px;
        background: #E2EAF3;
        padding: 0 20px;
        line-height: 30px;
        font-size: 14px;
        width: calc(100% - 290px - 140px - 20px);
        @include textEllipsis();
        .tips {
            color: #888;
            font-size: 12px;
        }
    }
}
.form-item-manage-container {
    @include flexLayout(flex, normal, normal);
    height: 100%;
    .container-left {
        width: 2.8rem;
        flex: 0 0 auto;
        .filter-input {
            width: 1.3rem;
            margin-right: 10px;
        }
        .container-left-body {
            margin-left: 4px;
            height: 100%;
            background: #fff;
            padding: 10px;

            .add-btn {
                float: right;
                margin-bottom: 14px;
            }

            .scroll-box {
                height: calc(100% - 50px);
                clear: both;
                overflow-y: auto;
            }
        }
    }
    .container-right {
        margin-left: 0.1rem;
        width: calc(100% - 2.9rem);
        height: 100%;
    }
}
</style>
